package com.mekya.sensorPlayer;

import java.util.ArrayList;


public class SignalDetector {
	private int minDataCount = 10;

	/**
	 * Get cross coefficient parameter of a data signal according to pattern signal
	 * data signal and pattern signal must have same sample rate
	 * @param data
	 * @param pattern
	 * @return
	 * @throws Exception 
	 */
	public float getCCCoefficient(float[] data, float[] pattern, int dataCount) throws Exception
	{
		if (data.length < minDataCount || pattern.length < minDataCount || dataCount < minDataCount) {	
			throw new Exception("There is no enough data to match");
		}
		if(dataCount > data.length) {
			dataCount = data.length;
		}
		int correlationLength = data.length;
		if (pattern.length < data.length) {
			correlationLength = pattern.length;
		}

		float meanData, meanPattern, sx, sy, sxy, denom, r;

		/* Calculate the mean of the two series data[], pattern[] */
		meanData = 0;
		meanPattern = 0;		   
		for (int i=0; i < correlationLength; i++) {
			meanData += data[i];
			meanPattern += pattern[i];
		}
		meanData = (float)meanData/correlationLength;
		meanPattern = (float)meanPattern/correlationLength;

		/* Calculate the denominator */
		sx = 0;
		sy = 0;
		for (int i=0; i < correlationLength; i++) {
			sx += (data[i] - meanData) * (data[i] - meanData);
			sy += (pattern[i] - meanPattern) * (pattern[i] - meanPattern);
		}
		denom = (float)(Math.sqrt(sx) * Math.sqrt(sy));
		sxy = 0;
		for (int i = 0; i < correlationLength; i++) 
		{
			sxy += (data[i] - meanData) * (pattern[i] - meanPattern);		       
		}
		r = sxy / denom;

		/* r is the correlation coefficient at "delay" */
		return r;		   
	}

	public int getMinDataCount() {
		return minDataCount;
	}

}
